package com.example.mobifin_busticket.views.activities;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.BusTicketManagaer;
import com.example.mobifin_busticket.MyApplication;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.Util;
import com.example.mobifin_busticket.R.layout;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.models.TicketDetailsModel;
import com.example.mobifin_busticket.views.dialogs.CancellationPolicy;
import com.example.mobifin_busticket.views.dialogs.CancellationPolicyDialog;
import com.google.common.io.LineReader;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class CancelTicketDetailsActivity extends MobifinActivity implements
		OnClickListener {
	String strTicketNo, formatededDate = "", strDatejourney = "", datejourney,
			strdoj, strcancellationPolicy, strDOJ;
	Boolean strPartialcallationAllow;
	Long DepartureTime;
	TicketDetailsModel ticketDetailsModel;
	TextView tvNewPNRNo, tvStatus, tvTotalFare, tvDepartureTime, tvTravelsName,
			tvToValue, tvFromValue, tvTravelContactNo, tvTicketNo,
			tvCancellationPOlicy, tvPartial, tvpassenger, tvpassengerage,
			tvpassengergender, tvseatno, tvticketStatus;
	Button btn_year, btn_date, btn_dayName, btn_cancel, btn_headerBack;
	LinearLayout llPassengerMain;
	ArrayList<TicketDetailsModel> ticketDetailsList;
	ArrayList<TicketDetailsModel> inventoryList;
	List<String> lstPassengerNames = null;
	Date searchedDate = null;
	SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
	View inflatedLayout;
	ScrollView scrlLayout;
	LinearLayout llError, llChildError;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cancel_ticket_details);
		tvNewPNRNo = (TextView) findViewById(R.id.tvNewPNRNo);
		tvStatus = (TextView) findViewById(R.id.tvStatus);
		tvTotalFare = (TextView) findViewById(R.id.tvTotalFare);
		tvDepartureTime = (TextView) findViewById(R.id.tvDepartureTime);
		tvTravelsName = (TextView) findViewById(R.id.tvTravelsName);
		tvTravelContactNo = (TextView) findViewById(R.id.tvTravelContactNo);
		tvToValue = (TextView) findViewById(R.id.tvToValue);
		tvFromValue = (TextView) findViewById(R.id.tvFromValue);
		tvTicketNo = (TextView) findViewById(R.id.tvTicketNo);
		tvCancellationPOlicy = (TextView) findViewById(R.id.tvCancellationPOlicy);
		tvPartial = (TextView) findViewById(R.id.tvPartial);
		btn_year = (Button) findViewById(R.id.btn_year);
		btn_date = (Button) findViewById(R.id.btn_date);
		btn_dayName = (Button) findViewById(R.id.btn_dayName);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_headerBack = (Button) findViewById(R.id.btn_headerBack);
		llPassengerMain = (LinearLayout) findViewById(R.id.llPassengerMain);
		llError = (LinearLayout) findViewById(R.id.llError);
		llChildError = (LinearLayout) findViewById(R.id.llChildERror);
		llError.setOnClickListener(this);
		tvCancellationPOlicy.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
		btn_headerBack.setOnClickListener(this);
		scrlLayout = (ScrollView) findViewById(R.id.scrlLayout);
		scrlLayout.setVisibility(View.GONE);
		strTicketNo = getIntent().getStringExtra("TicketNo");
		System.out.println("Ticket No from cancalltionDetails:" + strTicketNo);
		lstPassengerNames = new ArrayList<String>();
		ticketDetailsModel = new TicketDetailsModel();
		getTicketDetails();

	}

	protected void getTicketDetails() {
		ResponseListener ticketDetailsResponseFromSeatSeller = new ResponseListener() {
			Animation slide = AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.slidedown);
			int noofField = 0;
			String errorMessage = "";

			@Override
			public void onResponse(Object objTicketDetails) {
				// TODO Auto-generated method stub
				ArrayList<TicketDetailsModel> ticketDetailsList = (ArrayList<TicketDetailsModel>) objTicketDetails;
				System.out.println("Ticket Details:" + objTicketDetails);
				if (ticketDetailsList.isEmpty()) {
					if (MyApplication.getPd() != null
							&& MyApplication.getPd().isShowing()) {
						MyApplication.dismissProgressDialog();
					}
					llError.startAnimation(slide);
					scrlLayout.setVisibility(View.GONE);
					llError.setVisibility(View.VISIBLE);

					noofField = 1;
					errorMessage = getResources().getString(
							R.string.no_ticket_found);
					Util.errorFieldcreationSeatselect(
							CancelTicketDetailsActivity.this, llChildError,
							noofField, errorMessage);
				} else {
					setTicketDetails(ticketDetailsList);
				}

			}
		};

		// TODO Auto-generated method stub
		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager.getTicketDetails(CancelTicketDetailsActivity.this,
				ticketDetailsResponseFromSeatSeller, AppData.CONSUMERKEY,
				AppData.SECRETKEY, AppData.BASESEATURL + "/ticket?tin="
						+ strTicketNo, "TicketDetails");
	}

	private void setTicketDetails(
			ArrayList<TicketDetailsModel> ticketDetailsList) {
		// TODO Auto-generated method stub
		scrlLayout.setVisibility(View.VISIBLE);

		for (int i = 0; i < ticketDetailsList.size(); i++) {
			DepartureTime = Long.parseLong(ticketDetailsList.get(i)
					.getpickupTime().trim());
			tvNewPNRNo.setText(ticketDetailsList.get(i).getpnr() + "|");
			tvStatus.setText(ticketDetailsList.get(i).getstatus());
			tvTotalFare.setText("INR " + ticketDetailsList.get(i).getSeatFare()
					+ "|");
			tvDepartureTime.setText(convertTimeto12hourformat(DepartureTime));
			tvTravelsName.setText(ticketDetailsList.get(i).gettravels());
			tvToValue.setText(ticketDetailsList.get(i).getsourceCity());
			tvFromValue.setText(ticketDetailsList.get(i).getdestinationCity());
			tvTravelContactNo.setText(ticketDetailsList.get(i)
					.getpickUpContactNo());
			tvTicketNo.setText(ticketDetailsList.get(i).gettin());

			try {
				searchedDate = simpledateformat.parse(ticketDetailsList.get(i)
						.getdoj());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			datejourney = simpledateformat.format(searchedDate);
			strDatejourney = setSelctedDateinview(datejourney);

			if (ticketDetailsList.get(i).getstatus().toString()
					.equals("CANCELLED")) {
				btn_cancel.setVisibility(View.GONE);
				tvPartial.setVisibility(View.GONE);
			} else {
				btn_cancel.setVisibility(View.VISIBLE);
			}

			if (ticketDetailsList.get(i).getpartialCancellationAllowed()
					.toString().equals("false")) {
				tvPartial.setText("*Partial Cancellation Is Not Allowed");

			} else {
				tvPartial.setText("*Partial Cancellation Is Allowed");
			}
			inventoryList = ticketDetailsList.get(i).getinventoryList();
			addDynamicPassenger(inventoryList);

			strcancellationPolicy = ticketDetailsList.get(i)
					.getcancellationPolicy();
			strDOJ = ticketDetailsList.get(i).getdoj();
			strPartialcallationAllow = ticketDetailsList.get(i)
					.getpartialCancellationAllowed();

		}

	}

	private void addDynamicPassenger(ArrayList<TicketDetailsModel> inventoryList) {
		// TODO Auto-generated method stub
		for (int i = 0; i < inventoryList.size(); i++) {
			LayoutInflater inflater = LayoutInflater
					.from(CancelTicketDetailsActivity.this);
			inflatedLayout = inflater.inflate(
					R.layout.passenger_row_cancel_details, null);
			tvpassenger = (TextView) inflatedLayout
					.findViewById(R.id.tvTravellerName);
			tvpassengerage = (TextView) inflatedLayout
					.findViewById(R.id.tvTravllerAge);
			tvpassengergender = (TextView) inflatedLayout
					.findViewById(R.id.tvTravellerGender);
			tvseatno = (TextView) inflatedLayout
					.findViewById(R.id.tvTravellerSeatName);
			tvticketStatus = (TextView) inflatedLayout
					.findViewById(R.id.tvCancelOrBooked);

			tvpassenger.setText(inventoryList.get(i).gettravellerName());
			tvpassengerage.setText(inventoryList.get(i).getage());
			tvpassengergender.setText(inventoryList.get(i).getgender());
			tvseatno.setText(inventoryList.get(i).getTDseatName());
			tvticketStatus.setText(inventoryList.get(i).getstatus());
			inflatedLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!tvStatus.getText().toString().equals("CANCELLED")) {
						onClickPassengerLayout();
					}

				}
			});
			llPassengerMain.addView(inflatedLayout);
		}
	}

	protected void onClickPassengerLayout() {
		// TODO Auto-generated method stub
		Intent cancelSeatIntent = new Intent(CancelTicketDetailsActivity.this,
				CancelledSeatActivity.class);
		cancelSeatIntent.putExtra("TicketNo:", strTicketNo);
		cancelSeatIntent.putExtra("PNR no", tvNewPNRNo.getText().toString());
		cancelSeatIntent.putExtra("status", tvStatus.getText().toString());
		cancelSeatIntent
				.putExtra("TotalFare", tvTotalFare.getText().toString());
		cancelSeatIntent.putExtra("DepartureTime", tvDepartureTime.getText()
				.toString());
		cancelSeatIntent.putExtra("TravelsName", tvTravelsName.getText()
				.toString());
		cancelSeatIntent.putExtra("SourceName", tvToValue.getText().toString());
		cancelSeatIntent.putExtra("DestinationValue", tvFromValue.getText()
				.toString());
		cancelSeatIntent.putExtra("TravellerContactNo", tvTravelContactNo
				.getText().toString());
		cancelSeatIntent.putExtra("TicketNo", tvTicketNo.getText().toString());
		cancelSeatIntent.putExtra("YearButton", btn_year.getText().toString());
		cancelSeatIntent.putExtra("dateButton", btn_date.getText().toString());
		cancelSeatIntent.putExtra("dayNameButtom", btn_dayName.getText()
				.toString());
		cancelSeatIntent.putExtra("DateOfJourny", strDatejourney);
		cancelSeatIntent.putExtra("cancellationPolicy", strcancellationPolicy);
		cancelSeatIntent.putExtra("StrDOJ", strDOJ);
		cancelSeatIntent.putExtra("PartialCancellationAllow",
				strPartialcallationAllow);
		AppData.InventoryList = inventoryList;
		startActivity(cancelSeatIntent);

	}

	private String setSelctedDateinview(String datejourney) {
		// TODO Auto-generated method stub
		String monthName = "", dayName = "";
		try {
			Date date = simpledateformat.parse(datejourney);
			SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
			monthName = monthDate.format(date.getTime());

			SimpleDateFormat sdf = new SimpleDateFormat("EEE");
			dayName = sdf.format(date);
		} catch (java.text.ParseException e) {
			Log.e(AppData.EXCEPTION, e.toString(), e);
		}

		strdoj = dayName + ", " + ""
				+ datejourney.substring(Math.max(datejourney.length() - 2, 0))

				+ monthName + " " + datejourney.substring(0, 4).toString();
		btn_year.setText(monthName + " "
				+ datejourney.substring(0, 4).toString());
		btn_dayName.setText(dayName);
		btn_date.setText(datejourney.substring(Math.max(
				datejourney.length() - 2, 0)));
		return strdoj;
	}

	public static String convertTimeto12hourformat(Long time) {
		String actultime;
		int quotient, hour, minitue;
		quotient = (int) (time / 60);
		minitue = (int) (time % 60);
		hour = quotient % 24;
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minitue);
		Date mDate = new Date(c.getTimeInMillis());
		DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
		actultime = dateFormat.format(mDate);
		return actultime;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tvCancellationPOlicy:
			onClickCacellationPOlicy();
			break;

		case R.id.btn_headerBack:
			finish();
			break;
		case R.id.btn_cancel:
			onClickPassengerLayout();
			break;
		default:
			break;
		}
	}

	private void onClickCacellationPOlicy() {
		// TODO Auto-generated method stub
		CancellationPolicy cancellationPolicyDialog = new CancellationPolicy(
				CancelTicketDetailsActivity.this, tvDepartureTime.getText()
						.toString().trim(), strcancellationPolicy, strDOJ,
				strPartialcallationAllow);
		cancellationPolicyDialog.show();
	}

}
